import Queue from "./queue";

class PriorityQueueElement {
  constructor(ele, priority) {
    this.ele = ele;
    this.priority = priority;
  }
}

class PriorityQueue extends Queue {
  // 只需重写进队方法，其它方法与普通队列一致
  enqueue(ele, priority) {
    const element = new PriorityQueueElement(ele, priority);
    let added = false;
    // 如果队列为空，直接入队
    if (this.isEmpty()) {
      this.items.push(element);
    } else {
      // 如果队列不为空，需要和队列中已有的元素一一比较优先级
      for (let i = 0; i < this.size(); i++) {
        // 如果优先级比已有的元素的优先级高，则把它插入该元素的前面，并结束循环
        if (element.priority <= this.items[i].priority) {
          this.items.splice(i, 0, element);
          added = true;
          break;
        }
      }
      // 如果优先级比已有的元素的优先级低，则把它插入队列的后面
      if (!added) {
        this.items.push(element);
      }
    }
  }
}

export default PriorityQueue